﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Web;
using System.Data.SqlClient;
using Newtonsoft.Json;
using System.Text;
using System.Security.Cryptography;

namespace DHQGHN.Common
{
    public class Utils
    {
        public static String Master_DB_NAME = "master";
        public static String BuildConnectionString(string dataSource, String initialCataLog, String userId, String password)
        {
            return String.Format("data source={0};initial catalog={1};persist security info=True;user id={2};password={3};MultipleActiveResultSets=True", dataSource, initialCataLog, userId, password);
        }

        public static String BuildConnectionString(string dataSource, string userId, string password)
        {
            return String.Format("data source={0};persist security info=True;user id={1};password={2};MultipleActiveResultSets=True", dataSource, userId, password);
        }

        public static String BuildMasterConnectionString(String initialCataLog, String userId, String password)
        {
            return BuildConnectionString(Master_DB_NAME, initialCataLog, userId, password);
        }
        /// <summary>
        /// Lấy chuỗi từ trong file DefaultResource.resx
        /// </summary>
        /// <param name="resourceName">Tên của file resource, mặc định là "DefaultResource"</param>
        /// <param name="key">Từ khoá dùng để định nghĩa chuỗi</param>
        /// <returns>Chuỗi mang ý nghĩa tương ứng với từ khoá đầu vào</returns>
        public static string GetString(string key, string resourceName = "Localization")
        {
            ResourceManager rm = new ResourceManager("Resources." + resourceName, Assembly.Load("App_GlobalResources"));
            string s = rm == null ? key : rm.GetString(key);
            return string.IsNullOrWhiteSpace(s) ? key : s;
        }

        public static bool IntIsNullOrZeRo(int? p)
        {
            if (p == null || p == 0)
            {
                return true;
            }
            return false;
        }

        public static string SHA1Encode(string value)
        {
            var hash = System.Security.Cryptography.SHA1.Create();
            var encoder = new System.Text.ASCIIEncoding();
            var combined = encoder.GetBytes(value ?? "");
            return BitConverter.ToString(hash.ComputeHash(combined)).ToLower().Replace("-", "");
        }

        public static string MD5Encode(string value)
        {
            var hash = System.Security.Cryptography.MD5.Create();
            var encoder = new System.Text.ASCIIEncoding();
            var combined = encoder.GetBytes(value ?? "");
            return BitConverter.ToString(hash.ComputeHash(combined)).ToLower().Replace("-", "");
        }

        public static string CreatePasswordHash(string password)
        {
            HashAlgorithm hash = new SHA256Managed();
            byte[] plainTextBytes = System.Text.Encoding.UTF8.GetBytes(password.Trim());
            byte[] hashBytes = hash.ComputeHash(plainTextBytes);

            //in this string you got the encrypted password
            string hashValue = Convert.ToBase64String(hashBytes);
            
            return hashValue;
        }

        public static long DateTime2TimeStamp(DateTime date)
        {
            //var timeSpan = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0));
            //var timeSpan = (DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0));
            var timeSpan = (date - new DateTime(1970, 1, 1, 0, 0, 0));
            return (long)timeSpan.TotalSeconds;
        }

        public static long GetCurrentTimeNow()
        {
            try
            {
                return long.Parse(DateTime.Now.ToString("yyyyMMddHHmmss"));
            }
            catch
            {
                return 0;
            }

        }

        public static bool ParseStringToInt(string value)
        {
            try
            {
                int.Parse(value.Trim().ToString());
                return true;
            }
            catch
            {
                return false;
            }
        }

        public static bool ParseStringToIntOfDate(string value)
        {
            try
            {
                if (value != null && !value.Equals("-1"))
                {
                    CultureInfo provider = CultureInfo.InvariantCulture;
                    string format = "yyyyMMdd";
                    DateTime.ParseExact(value.Trim().ToString(), format, provider);
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        public static bool TestConnection(string connString)
        {
            using (SqlConnection conn = new SqlConnection(connString))
            {
                try
                {
                    conn.Open();
                    return true;
                }
                catch (Exception ex)
                {
                    return false;
                }
                finally
                {
                    conn.Close();
                    conn.Dispose();
                }
            }
        }

        public static bool IsNullOrEmptyOverride(string value)
        {
            if (value == null)
            {
                return true;
            }
            else if (value.Trim().ToString().Length == 0)
            {
                return true;
            }
            return false;
        }

        public static string ParseJSONFromListObject<T>(List<T> arr)
        {
            string res = "";
            try
            {
                if (arr != null && arr.Count > 0)
                {
                    res = JsonConvert.SerializeObject(arr);
                    res = res.Replace("\":\"-1\"", "\":null");
                    res = res.Replace("\":\"\"", "\":null");                  
                }
            }
            catch
            {
                res = "";
            }
            return res;
        }

        public static string ParseJSONFromObject<T>(T ob)
        {
            string res = "";
            try
            {
                res = JsonConvert.SerializeObject(ob);
            }
            catch
            {
                res = "";
            }
            return res;
        }

        /// <summary>
        /// Chuyen ngay thang dang kieu chuoi sang dang kieu int. Tra ve 0 neu tham so co gia tri rong
        /// </summary>
        /// <param name="date">tham so dang dd/mm/yyyy</param>
        /// <param name="spliter">ky tu phan cach ngay thang</param>
        /// <returns></returns>
        public static int ConvertDateStringToInt(string date, string spliter, int type = 1)
        {
            if (string.IsNullOrEmpty(date))
            {
                if (type == 1)
                {
                    return 19000101;
                }

                return 99991231;

            }
            string[] dateElements = date.Split(new string[] { spliter }, StringSplitOptions.RemoveEmptyEntries);
            string year = dateElements[2];
            string month = Format(dateElements[1].Trim());
            string day = Format(dateElements[0].Trim());
            string dateString = year + month + day;
            int result = Convert.ToInt32(dateString);

            return result;
        }

        private static string Format(string value)
        {
            string result = value;
            if (result.Length < 2)
            {
                result += "0";
            }

            return result;
        }

        /// <summary>
        /// Chuyen ngay thang tu dang kieu int sang dang chuoi. Tra ve rong neu tham so co gia tri 0
        /// </summary>
        /// <param name="date">tham so kieu int dang yyyymmdd</param>
        /// <returns></returns>
        public static string ConvertDateIntToString(int date, string spliter)
        {
            if (date == 0 || date == 19000101 || date == 99991231)
            {
                return "";
            }
            string dateString = date.ToString();
            if (dateString.Length < 8)
            {
                return "";
            }
            int start = 0;
            int len = 4;
            List<string> items = new List<string>();
            do
            {
                items.Add(dateString.Substring(start, len));
                start += len;
                len = 2;
            } while (dateString.Length > start);

            StringBuilder result = new StringBuilder("");
            string day = items[2];
            string month = items[1];
            string year = items[0];
            result.Append(day);
            result.Append(spliter);
            result.Append(month);
            result.Append(spliter);
            result.Append(year);

            return result.ToString();
        }

        public static Dictionary<string, string> SplitDate(string date, string format = "dd/mm/yyy")
        {
            Dictionary<string, string> container = new Dictionary<string, string>();
            if (string.IsNullOrEmpty(date))
            {
                throw new ArgumentNullException();
            }
            string[] formater = format.Split(new string[] { "/", "-" }, StringSplitOptions.RemoveEmptyEntries);
            string[] splitedDate = date.Split(new string[] { "/", "-" }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < formater.Length; i++)
            {
                container.Add(formater[i], splitedDate[i]);
            }

            return container;
        }

        public static DateTime ConvertStringToDateTime(string date, string format = "dd/mm/yyyy")
        {
            if (date == null)
                return DateTime.MinValue;
            
            Dictionary<string, string> dateItem = SplitDate(date, format);
            DateTime dt = new DateTime(Convert.ToInt32(dateItem["yyyy"]),
                Convert.ToInt32(dateItem["mm"]), Convert.ToInt32(dateItem["dd"]));

            return dt;
        }
    }
}